package com.wo.cloud.tenant.interceptor;

import com.wo.cloud.core.constant.TenantConstant;
import com.wo.cloud.core.context.TenantContextHolder;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/4/25 10:36
 * Description: 将http header 中租户ID 通过 RestTemplate 方式进行传递
 */
public class TenantRequestInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

        // 获取上个服务的tenantId, 传递到下个服务中
        if (TenantContextHolder.getTenantId() != null) {
            request.getHeaders().set(TenantConstant.TENANT_ID_HEADER, String.valueOf(TenantContextHolder.getTenantId()));
        }

        return execution.execute(request, body);
    }
}
